package 锁;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.locks.LockSupport;

import org.junit.Test;

/**
 * 用于阻塞与唤醒线程
 * <p>
 * Title: LockSupportTest
 * </p>
 *
 * @author zj
 * @date 2019年10月2日
 */
public class LockSupportTest {
    volatile int num = 0;
    LinkedBlockingDeque<Thread> queue = new LinkedBlockingDeque<>();

    public static void main(String[] args) throws InterruptedException {
        new LockSupportTest().test01();
    }

    @Test
    public void test01() throws InterruptedException {
        new Thread(() -> {
            while (num < 100) {
                System.out.println(num++);
                if (num % 10 == 0) {
                    System.out.println("准备休息~");
                    System.out.println(Thread.currentThread());
                    queue.add(Thread.currentThread());
                    LockSupport.park();
                }
            }
        }).start();

        Thread t2 = new Thread(() -> {
            while (num < 100) {
                Thread t = null;
                try {
                    t = queue.take();
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("已经休息够了 起来干活~");
                LockSupport.unpark(t);
            }
        });
        t2.start();
        t2.join();
    }
}
